import axios from 'axios'
import render from './index.art'

/* 
    读取query参数指定参数名的值
    */
function getQueryValue(name) {
  var str = location.href.split('?');
  var query = str[1];
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == name) {
      return pair[1];
    }
  }
  return false;
}

/* 
    根据参数请求获取图书信息显示
    */
async function getBook() {
  // 得到id参数
  const id = getQueryValue('id');
  // 发ajax请求
  const response = await axios(`http://localhost:8080/book/${id}`);
  const book = response.data.data;
  // console.log(book)
  // 渲染模板
  // const html = template('form-content', { book });
  const html = render({ book });
  // 插入到div中
  document.getElementById('form').innerHTML = html;
}

getBook();

document.getElementById('btn').onclick = async () => {
  // 收集数据
  const _id = document.getElementById('_id').value;
  const name = document.getElementById('name').value;
  const author = document.getElementById('author').value;
  const price = document.getElementById('price').value;
  // 提交修改图书的ajax请求
  await axios({
    url: 'http://localhost:8080/book',
    method: 'PUT',
    data: { _id, name, author, price },
  });
  // 成功后, 跳转到books页面
  window.location = '/books.html';
};
